﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Fayshine.VA.Helpers;
using Fayshine.VA.Models;
using Fayshine.VA.RIAService.Web;
using Fayshine.VA.ViewModels;
using Visifire.Charts;
using LocalBusyIndicator = Fayshine.VA.Controls.BusyIndicator;

namespace Fayshine.VA.Views.Reports
{
    public partial class WeekReports : Page
    {
        private bool m_IsFinshed1 = false;
        private bool m_IsFinshed2 = false;
        private StatisticsReportViewModel m_ViewModel;

        public WeekReports()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(WeekReports_Loaded);
        }

        #region Event Methods

        private void WeekReports_Loaded(object sender, RoutedEventArgs e)
        {
            LocalBusyIndicator indicator = Application.Current.RootVisual as LocalBusyIndicator;
            indicator.IsBusy = true;
            datePicker.SelectedDate = DateTime.Now;
            m_ViewModel = new StatisticsReportViewModel();
            m_ViewModel.ResetHisotryChartEvent += new ResetHistoryChartEventHandler(m_ViewModel_ResetHisotryChartEvent);
            m_ViewModel.AppendHistoryPassengerFlow += new AppendHistoryPassengerFlowEventHandler(m_ViewModel_AppendHistoryPassengerFlow);
            m_ViewModel.AppendMultiHistoryPassenger += new AppendMultiHistoryPassengerEventHandler(m_ViewModel_AppendMultiHistoryPassenger);
            this.DataContext = m_ViewModel;

            m_ViewModel.GetAllAreas();
        }

        private void m_ViewModel_AppendHistoryPassengerFlow(string title, bool isIn, List<HistoryPassengerFlow> firstHistoryPassengerFlow, List<HistoryPassengerFlow> secondHistoryPassengerFlow)
        {
            this.Dispatcher.BeginInvoke(delegate()
            {
                SetMonthInChart(firstHistoryPassengerFlow);
                SetStrandarChart(firstHistoryPassengerFlow);
                SetWeekDayChart();
                m_IsFinshed1 = true;
                ResetBusyIndicator();
            });
        }

        private void m_ViewModel_AppendMultiHistoryPassenger(string title, bool isIn, params List<HistoryPassengerFlow>[] historyPassengerFlows)
        {
            this.Dispatcher.BeginInvoke(delegate()
            {
                var thisWeekDayPassneger = historyPassengerFlows[0];
                var lastWeekDayPassenger = historyPassengerFlows[1];
                var lastYearWeekDayPassenger = historyPassengerFlows[2];
                var thisYearWeekPassneger = historyPassengerFlows[3];
                var lastYearWeekPassenger = historyPassengerFlows[4];
                var thisWeekGatePassenger = historyPassengerFlows[5];

                //Set Week and Year Chart
                SetWeekCompareChart(thisYearWeekPassneger, lastYearWeekPassenger);
                SetThisWeekDayCompareChart(thisWeekDayPassneger, lastWeekDayPassenger, lastYearWeekDayPassenger);
                SetWeekGateInOurCompareChart(thisWeekGatePassenger);
                SetWeekGateProcentChart(thisWeekGatePassenger);
                SetYearWeekCompareChart(thisYearWeekPassneger, lastYearWeekPassenger);
                SetAllPassengerSexChart();
                SetPassengerAgeChart();
                m_IsFinshed2 = true;
                ResetBusyIndicator();
            });


        }

        private void m_ViewModel_ResetHisotryChartEvent()
        {
            this.Dispatcher.BeginInvoke(delegate()
            {

                if (vcWeekCompare != null)
                {
                    vcWeekCompare.AxesX.Clear();
                    vcWeekCompare.TrendLines.Clear();
                    vcWeekCompare.Series.Clear();
                    vcWeekCompare.Titles.Clear();
                }

                if (vcWeekDay != null)
                {
                    vcWeekDay.AxesX.Clear();
                    vcWeekDay.TrendLines.Clear();
                    vcWeekDay.Series.Clear();
                    vcWeekDay.Titles.Clear();
                }

                if (vcGateCompare != null)
                {
                    vcGateCompare.AxesX.Clear();
                    vcGateCompare.TrendLines.Clear();
                    vcGateCompare.Series.Clear();
                    vcGateCompare.Titles.Clear();
                }

                if (vcGatePrecentCompare != null)
                {
                    vcGatePrecentCompare.AxesX.Clear();
                    vcGatePrecentCompare.TrendLines.Clear();
                    vcGatePrecentCompare.Series.Clear();
                    vcGatePrecentCompare.Titles.Clear();
                }

                if (vcGatePrecentCompare2 != null)
                {
                    vcGatePrecentCompare2.AxesX.Clear();
                    vcGatePrecentCompare2.TrendLines.Clear();
                    vcGatePrecentCompare2.Series.Clear();
                    vcGatePrecentCompare2.Titles.Clear();
                }

                if (vcWeekDayDurationChart != null)
                {
                    vcWeekDayDurationChart.AxesX.Clear();
                    vcWeekDayDurationChart.TrendLines.Clear();
                    vcWeekDayDurationChart.Series.Clear();
                    vcWeekDayDurationChart.Titles.Clear();
                }
                if (vcWeekInChart != null)
                {
                    vcWeekInChart.AxesX.Clear();
                    vcWeekInChart.TrendLines.Clear();
                    vcWeekInChart.Series.Clear();
                    vcWeekInChart.Titles.Clear();
                }
                if (vcStrandChart != null)
                {
                    vcStrandChart.AxesX.Clear();
                    vcStrandChart.TrendLines.Clear();
                    vcStrandChart.Series.Clear();
                    vcStrandChart.Titles.Clear();
                }

                if (vcEveryWeek != null)
                {
                    vcEveryWeek.AxesX.Clear();
                    vcEveryWeek.TrendLines.Clear();
                    vcEveryWeek.Series.Clear();
                    vcEveryWeek.Titles.Clear();
                }
                if (vcThisWeekSex != null)
                {
                    vcThisWeekSex.AxesX.Clear();
                    vcThisWeekSex.TrendLines.Clear();
                    vcThisWeekSex.Series.Clear();
                    vcThisWeekSex.Titles.Clear();
                }
                if (vcLastWeekSex != null)
                {
                    vcLastWeekSex.AxesX.Clear();
                    vcLastWeekSex.TrendLines.Clear();
                    vcLastWeekSex.Series.Clear();
                    vcLastWeekSex.Titles.Clear();
                }
                if (vcLastYearSex != null)
                {
                    vcLastYearSex.AxesX.Clear();
                    vcLastYearSex.TrendLines.Clear();
                    vcLastYearSex.Series.Clear();
                    vcLastYearSex.Titles.Clear();
                }

                if (vcWeekAgeChart != null)
                {
                    vcWeekAgeChart.AxesX.Clear();
                    vcWeekAgeChart.TrendLines.Clear();
                    vcWeekAgeChart.Series.Clear();
                    vcWeekAgeChart.Titles.Clear();
                }

            });
        }

        private void cmbAreas_DropDownClosed(object sender, EventArgs e)
        {
            if (m_ViewModel != null)
            {
                List<area> selectedArea = new List<area>();
                var selectAreaExt = m_ViewModel.AreaExtends.Where(a => a.IsSelected).ToList();
                selectAreaExt.ForEach(b =>
                {
                    area temp = b.Tag as area;
                    selectedArea.Add(temp);
                });

                if (selectedArea.Count > 0)
                {
                    cbItemDisplay.Content = selectedArea.Count > 1 ? selectedArea[0].Name + "..." : selectedArea[0].Name;

                }
                else
                {
                    cbItemDisplay.Content = string.Empty;
                }
                cmbAreas.SelectedItem = null;
                cmbAreas.SelectedItem = cbItemDisplay;

                m_ViewModel.SelectAreasChanged(selectedArea);
            }
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            string msg = string.Empty;
            
            m_ViewModel.UpdateCheckedAreas();

            if (!FayshineManager.Instance.ValidateAreaGateInputs(m_ViewModel.CheckedAreas,
                m_ViewModel.CheckedGates, ref msg))
            {
                MessageBox.Show(msg);
            }
            else
            {
                DateTime dateTime = datePicker.SelectedDate.Value;
                dateTime = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, 0, 0, 0);
                int weekNum = FayshineManager.Instance.GetWeekNumber(dateTime);
                DateTime startTime = dateTime;
                DateTime endTime = dateTime;
                m_ViewModel.GetWeekStartAndEndTime(dateTime, out startTime, out endTime);
                lblTitleTop.Text = GetChartSubTitle() + "客流周报表";
                endTime = endTime.AddDays(-1);
                lblTitleTop2.Text = dateTime.Year + "年第" + weekNum + "周（" + startTime.ToShortDateString() + "至" + endTime.ToShortDateString() + ")";

                LocalBusyIndicator indicator = Application.Current.RootVisual as LocalBusyIndicator;
                indicator.IsBusy = true;
                m_IsFinshed1 = false;
                m_IsFinshed2 = false;
                m_ViewModel.RefreshWeekReport(true, dateTime);
            }
        }

        #endregion

        #region Private Methods

        private void ResetBusyIndicator()
        {
            if (m_IsFinshed2 && m_IsFinshed1)
            {
                LocalBusyIndicator indicator = Application.Current.RootVisual as LocalBusyIndicator;
                indicator.IsBusy = false;
            }
        }

        private void SetWeekCompareChart(List<HistoryPassengerFlow> thisYearWeekPassneger, List<HistoryPassengerFlow> lastYearWeekPassenger)
        {
            DateTime time = datePicker.SelectedDate.Value;
            int weekNum = FayshineManager.Instance.GetWeekNumber(time);
            List<HistoryPassengerFlow> sourcePassengers = new List<HistoryPassengerFlow>();

            HistoryPassengerFlow thisWeek = new HistoryPassengerFlow();
            thisWeek.DisplayTitle = "本周";
            thisWeek.AllInOut = thisYearWeekPassneger.Where(t => t.MonthOrDayOrWeek == weekNum).First().AllInOut;
            sourcePassengers.Add(thisWeek);

            HistoryPassengerFlow lastWeek = new HistoryPassengerFlow();
            lastWeek.DisplayTitle = "上周";
            lastWeek.AllInOut = thisYearWeekPassneger.Where(t => t.MonthOrDayOrWeek == weekNum-1).First().AllInOut;
            sourcePassengers.Add(lastWeek);

            HistoryPassengerFlow lastYearWeek = new HistoryPassengerFlow();
            lastYearWeek.DisplayTitle = "去年同期";
            lastYearWeek.AllInOut = lastYearWeekPassenger.Where(t => t.MonthOrDayOrWeek == weekNum).First().AllInOut;
            sourcePassengers.Add(lastYearWeek);

            HistoryPassengerFlow thisYearAve = new HistoryPassengerFlow();
            thisYearAve.DisplayTitle = "今年平均";
            thisYearAve.AllInOut = Convert.ToInt32(thisYearWeekPassneger.Average(t => t.AllInOut));
            sourcePassengers.Add(thisYearAve);

            HistoryPassengerFlow lastYearAve = new HistoryPassengerFlow();
            lastYearAve.DisplayTitle = "今年平均";
            lastYearAve.AllInOut = Convert.ToInt32(lastYearWeekPassenger.Average(t => t.AllInOut));
            sourcePassengers.Add(lastYearAve);

            Title vcChart1Title = new Visifire.Charts.Title();
            vcChart1Title.Text = time.Year + "年第" + weekNum + "周" + "同期客流对比";
            vcWeekCompare.Titles.Add(vcChart1Title);

            DataSeries series = ChartHelper.GetDataSeries(RenderAs.Column, "", ChartValueTypes.Auto);
            series.DataMappings.Add(ChartHelper.GetDataMapping("AxisXLabel", "DisplayTitle"));
            series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "AllInOut"));
            series.DataSource = sourcePassengers;
            vcWeekCompare.Series.Add(series);

        }

        private void SetThisWeekDayCompareChart(List<HistoryPassengerFlow> thisWeekDayPassenger, List<HistoryPassengerFlow> lastWeekDayPassenger,List<HistoryPassengerFlow> lastYearWeekDayPassenger)
        {
            DateTime time = datePicker.SelectedDate.Value;
            int weekNum = FayshineManager.Instance.GetWeekNumber(time);

            Title vcChart1Title = new Visifire.Charts.Title();
            vcChart1Title.Text = GetChartSubTitle() + "本周上周每日客流比较";
            vcWeekDay.Titles.Add(vcChart1Title);

            DataSeries series = ChartHelper.GetDataSeries(RenderAs.Column, "本周", ChartValueTypes.Auto);
            series.DataMappings.Add(ChartHelper.GetDataMapping("AxisXLabel", "DisplayTitle"));
            series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "AllInOut"));
            series.DataSource = thisWeekDayPassenger;
            vcWeekDay.Series.Add(series);

            DataSeries series1 = ChartHelper.GetDataSeries(RenderAs.Column, "上周", ChartValueTypes.Auto);
            series1.DataMappings.Add(ChartHelper.GetDataMapping("AxisXLabel", "DisplayTitle"));
            series1.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "AllInOut"));
            series1.DataSource = lastWeekDayPassenger;
            vcWeekDay.Series.Add(series1);

            DataSeries series2 = ChartHelper.GetDataSeries(RenderAs.Column, "去年同期", ChartValueTypes.Auto);
            series2.DataMappings.Add(ChartHelper.GetDataMapping("AxisXLabel", "DisplayTitle"));
            series2.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "AllInOut"));
            series2.DataSource = lastYearWeekDayPassenger;
            vcWeekDay.Series.Add(series2);
        }

        private void SetWeekGateInOurCompareChart(List<HistoryPassengerFlow> thisWeekGatePassengerFlows)
        {
            List<HistoryPassengerFlow> sources = thisWeekGatePassengerFlows.OrderBy(o => o.DisplayTitle).ToList();

            DateTime time = datePicker.SelectedDate.Value;
            int weekNum = FayshineManager.Instance.GetWeekNumber(time);

            string title1 = GetChartSubTitle();

            Title vcChart1Title = new Visifire.Charts.Title();
            vcChart1Title.Text = time.Year + "年第" + weekNum+ "周" + title1 + " 各通道进出客流对比";
            vcGateCompare.Titles.Add(vcChart1Title);

            DataSeries series = ChartHelper.GetDataSeries(RenderAs.Column, "进", ChartValueTypes.Auto);
            series.DataMappings.Add(ChartHelper.GetDataMapping("AxisXLabel", "DisplayTitle"));
            series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "InCount"));
            series.DataSource = sources;
            vcGateCompare.Series.Add(series);

            DataSeries series2 = ChartHelper.GetDataSeries(RenderAs.Column, "出", ChartValueTypes.Auto);
            series2.DataMappings.Add(ChartHelper.GetDataMapping("AxisXLabel", "DisplayTitle"));
            series2.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "OutCount"));
            series2.DataSource = sources;
            vcGateCompare.Series.Add(series2);

        }

        private void SetWeekGateProcentChart(List<HistoryPassengerFlow> thisWeekGatePassengerFlows)
        {
            List<HistoryPassengerFlow> sources = thisWeekGatePassengerFlows.OrderBy(o => o.DisplayTitle).ToList();
            DateTime time = datePicker.SelectedDate.Value;
            int weekNum = FayshineManager.Instance.GetWeekNumber(time);
            string title1 = GetChartSubTitle();

            Title vcChart1Title = new Visifire.Charts.Title();
            vcChart1Title.Text = time.Year + "年第" + weekNum + "周" + title1 + " 进客流百分比";
            vcGatePrecentCompare.Titles.Add(vcChart1Title);

            DataSeries series = ChartHelper.GetDataSeries(RenderAs.Pie, "进", ChartValueTypes.Auto);
            series.DataMappings.Add(ChartHelper.GetDataMapping("AxisXLabel", "DisplayTitle"));
            series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "InCount"));
            series.LabelText = "#AxisXLabel (#Percentage%)";
            series.DataSource = sources;
            vcGatePrecentCompare.Series.Add(series);

            Title vcChart1Title2 = new Visifire.Charts.Title();
            vcChart1Title2.Text = time.Year + "年第" + weekNum + "周" + title1 + " 出客流百分比";
            vcGatePrecentCompare2.Titles.Add(vcChart1Title2);

            DataSeries series2 = ChartHelper.GetDataSeries(RenderAs.Pie, "出", ChartValueTypes.Auto);
            series2.DataMappings.Add(ChartHelper.GetDataMapping("AxisXLabel", "DisplayTitle"));
            series2.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "OutCount"));
            series2.LabelText = "#AxisXLabel (#Percentage%)";
            series2.DataSource = sources;
            vcGatePrecentCompare2.Series.Add(series2);

        }

        private void SetYearWeekCompareChart(List<HistoryPassengerFlow> thisYearWeekPassenger, List<HistoryPassengerFlow> lastYearWeekPassenger)
        {
            DateTime time = datePicker.SelectedDate.Value;
            string title1 = GetChartSubTitle();

            Axis xAxis = new Axis();
            xAxis.AxisMinimum = 0;
            xAxis.AxisMaximum = FayshineManager.Instance.GetYearWeekCount(time.Year);

            xAxis.IntervalType = IntervalTypes.Number;
            xAxis.Interval = 1;
            vcEveryWeek.AxesX.Add(xAxis);

            Title vcChart1Title = new Visifire.Charts.Title();
            vcChart1Title.Text = time.Year + "年" + title1 + "历周客流分布图";
            vcEveryWeek.Titles.Add(vcChart1Title);

            DataSeries series = ChartHelper.GetDataSeries(RenderAs.Line, "今年", ChartValueTypes.Numeric);
            series.DataMappings.Add(ChartHelper.GetDataMapping("XValue", "MonthOrDayOrWeek"));
            series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "AllInOut"));
            series.DataSource = thisYearWeekPassenger;

            DataSeries series2 = ChartHelper.GetDataSeries(RenderAs.Line, "去年", ChartValueTypes.Numeric);
            series2.DataMappings.Add(ChartHelper.GetDataMapping("XValue", "MonthOrDayOrWeek"));
            series2.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "AllInOut"));
            series2.DataSource = lastYearWeekPassenger;

            vcEveryWeek.Series.Add(series);
        }

        private void SetMonthInChart(List<HistoryPassengerFlow> historyPassengerFlows)
        {
            Axis xAxis = new Axis();
            DateTime minDateTime = historyPassengerFlows.Select(s => s.HistoryTime).Min();
            DateTime maxDateTime = historyPassengerFlows.Select(s => s.HistoryTime).Max();
            xAxis.AxisMinimum = minDateTime;
            xAxis.AxisMaximum = maxDateTime;
            if (maxDateTime.Year == minDateTime.Year && maxDateTime.Month == minDateTime.Month &&
                maxDateTime.Day == minDateTime.Day)
            {
                xAxis.ValueFormatString = "HH:mm";
                xAxis.IntervalType = IntervalTypes.Hours;
                xAxis.Interval = 1;
            }
            else
            {
                xAxis.IntervalType = IntervalTypes.Hours;
                xAxis.Interval = 4;
            }
            vcWeekInChart.AxesX.Add(xAxis);

            int max = 0;
            double avg = 0;
            max = historyPassengerFlows.Select(s => s.InCount).Max();
            avg = historyPassengerFlows.Select(s => s.InCount).Average();

            DateTime time = datePicker.SelectedDate.Value;
            int weekNum = FayshineManager.Instance.GetWeekNumber(time);
            string title1 = GetChartSubTitle();

            Title vcChart1Title = new Visifire.Charts.Title();
            vcChart1Title.Text = time.Year + "年第" + weekNum + "周" + title1 + " 进客流分布图";
            vcWeekInChart.Titles.Add(vcChart1Title);

            TrendLine maxLine = new TrendLine();
            maxLine.Value = max;
            maxLine.LabelText = "最大:" + max.ToString();
            maxLine.FlowDirection = System.Windows.FlowDirection.LeftToRight;
            maxLine.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;

            TrendLine avgLine = new TrendLine();
            avgLine.Value = avg;
            avgLine.LabelText = "平均:" + Convert.ToInt32(avg).ToString();
            avgLine.FlowDirection = System.Windows.FlowDirection.LeftToRight;
            vcWeekInChart.TrendLines.Add(maxLine);
            vcWeekInChart.TrendLines.Add(avgLine);

            var selectedAreas = this.m_ViewModel.AreaExtends.Where(a => a.IsSelected).ToList();
            if (selectedAreas.Count > 1)
            {
                selectedAreas.each(s => {

                    DataSeries tempSeries = ChartHelper.GetDataSeries(RenderAs.Line, s.Name, ChartValueTypes.Time);
                    tempSeries.DataMappings.Add(ChartHelper.GetDataMapping("XValue", "HistoryTime"));
                    tempSeries.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "InCount"));
                    tempSeries.DataSource = m_ViewModel.GetWeekAnyDuarationPassengersByArea(s.ID, time);
                    vcWeekInChart.Series.Add(tempSeries);

                });
            }

            DataSeries series = ChartHelper.GetDataSeries(RenderAs.Line, "所选店铺（和）", ChartValueTypes.Time);
            series.DataMappings.Add(ChartHelper.GetDataMapping("XValue", "HistoryTime"));
            series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "InCount"));
            series.DataSource = historyPassengerFlows;
            vcWeekInChart.Series.Add(series);
        }

        private void SetStrandarChart(List<HistoryPassengerFlow> historyPassengerFlow)
        {
            Axis xAxis = new Axis();
            DateTime minDateTime = historyPassengerFlow.Select(s => s.HistoryTime).Min();
            DateTime maxDateTime = historyPassengerFlow.Select(s => s.HistoryTime).Max();
            xAxis.AxisMinimum = minDateTime;
            xAxis.AxisMaximum = maxDateTime;
            if (maxDateTime.Year == minDateTime.Year && maxDateTime.Month == minDateTime.Month &&
                maxDateTime.Day == minDateTime.Day)
            {
                xAxis.ValueFormatString = "HH:mm";
                xAxis.IntervalType = IntervalTypes.Hours;
                xAxis.Interval = 1;
            }
            else
            {
                xAxis.IntervalType = IntervalTypes.Hours;
                xAxis.Interval = 4;
            }
            vcStrandChart.AxesX.Add(xAxis);

            DateTime time = datePicker.SelectedDate.Value;
            int weekNum = FayshineManager.Instance.GetWeekNumber(time);
            string title1 = GetChartSubTitle();

            Title vcChart1Title = new Visifire.Charts.Title();
            vcChart1Title.Text = time.Year + "年第" + weekNum + "周" + title1 + " 滞留人数分布图";
            vcStrandChart.Titles.Add(vcChart1Title);

            //DataSeries accInSeries = ChartHelper.GetDataSeries(RenderAs.Area, "累计进", ChartValueTypes.Time);
            //accInSeries.DataMappings.Add(ChartHelper.GetDataMapping("XValue", "HistoryTime"));
            //accInSeries.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "AccumulateInCount"));
            //accInSeries.DataSource = historyPassengerFlow;

            //DataSeries accOutSeries = ChartHelper.GetDataSeries(RenderAs.Area, "累计出", ChartValueTypes.Time);
            //accOutSeries.DataMappings.Add(ChartHelper.GetDataMapping("XValue", "HistoryTime"));
            //accOutSeries.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "AccumulateOutCount"));
            //accOutSeries.DataSource = historyPassengerFlow;

            var selectedAreas = this.m_ViewModel.AreaExtends.Where(a => a.IsSelected).ToList();
            if (selectedAreas.Count > 1)
            {
                selectedAreas.each(s =>
                {

                    DataSeries tempSeries = ChartHelper.GetDataSeries(RenderAs.Line, s.Name, ChartValueTypes.Time);
                    tempSeries.DataMappings.Add(ChartHelper.GetDataMapping("XValue", "HistoryTime"));
                    tempSeries.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "StrandedCount"));
                    tempSeries.DataSource = m_ViewModel.GetWeekAnyDuarationPassengersByArea(s.ID, time);
                    vcStrandChart.Series.Add(tempSeries);

                });
            }

            DataSeries strandedSeries = ChartHelper.GetDataSeries(RenderAs.Line, "滞留人数", ChartValueTypes.Time);
            strandedSeries.DataMappings.Add(ChartHelper.GetDataMapping("XValue", "HistoryTime"));
            strandedSeries.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "StrandedCount"));
            strandedSeries.DataSource = historyPassengerFlow;
            //vcStrandChart.Series.Add(accInSeries);
            //vcStrandChart.Series.Add(accOutSeries);
            vcStrandChart.Series.Add(strandedSeries);
        }

        private void SetAllPassengerSexChart()
        {
            DateTime dateTime = datePicker.SelectedDate.Value;
            dateTime = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, 0, 0, 0);

           //this week
            DateTime startTime = dateTime;
            DateTime endTime = dateTime;
            m_ViewModel.GetWeekStartAndEndTime(dateTime, out startTime, out endTime);
            SetPassengerSexChart("本周男女客流占比图", startTime, endTime, vcThisWeekSex);

            //Last week
            startTime = dateTime.AddDays(-7);
            endTime = dateTime.AddDays(-7);
            m_ViewModel.GetWeekStartAndEndTime(dateTime.AddDays(-7), out startTime, out startTime);
            SetPassengerSexChart("上周男女客流占比图", startTime, endTime, vcLastWeekSex);

            //Last Year
            startTime = dateTime.AddYears(-1);
            endTime = dateTime.AddYears(-1);
            m_ViewModel.GetWeekStartAndEndTime(dateTime.AddYears(-1), out startTime, out startTime);
            SetPassengerSexChart("去年同期", startTime, endTime, vcLastYearSex);

        }

        private void SetPassengerSexChart(string title,DateTime startTime,DateTime endTime,Chart vcChart)
        {
            List<HistoryPassengerFlow> sexHistoryPassengerFlows = m_ViewModel.GetPassengerflowsBySex(startTime, endTime);

            Title vcChart1Title = new Visifire.Charts.Title();
            vcChart1Title.Text = title;
            vcChart.Titles.Add(vcChart1Title);

            DataSeries series = ChartHelper.GetDataSeries(RenderAs.Pie, "客流", ChartValueTypes.Auto);
            series.DataMappings.Add(ChartHelper.GetDataMapping("AxisXLabel", "SexName"));
            series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "AllInOut"));
            series.LabelText = "#AxisXLabel (#Percentage%)";
            series.DataSource = sexHistoryPassengerFlows;
            vcChart.Series.Add(series);
        }

        private void SetPassengerAgeChart()
        {
            DateTime dateTime = datePicker.SelectedDate.Value;
            dateTime = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, 0, 0, 0);
            
            DateTime startTime = dateTime;
            DateTime endTime = dateTime;
            m_ViewModel.GetWeekStartAndEndTime(dateTime, out startTime, out endTime);
            List<HistoryPassengerFlow> ageHistoryPassengerFlows = m_ViewModel.GetAgeDurationPassengerFlow(startTime, endTime);

            Axis xAxis = new Axis();
            xAxis.AxisMinimum = 0;
            xAxis.AxisMaximum = 120;

            xAxis.IntervalType = IntervalTypes.Number;
            xAxis.Interval = 5;

            vcWeekAgeChart.AxesX.Add(xAxis);

            Title vcChart1Title = new Visifire.Charts.Title();
            vcChart1Title.Text = "本周/上周各年龄段客流图";
            vcWeekAgeChart.Titles.Add(vcChart1Title);

            DataSeries series = ChartHelper.GetDataSeries(RenderAs.Line, "本周", ChartValueTypes.Numeric);
            series.DataMappings.Add(ChartHelper.GetDataMapping("XValue", "Age"));
            series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "AllInOut"));
            series.DataSource = ageHistoryPassengerFlows;
            vcWeekAgeChart.Series.Add(series);

            startTime = dateTime.AddDays(-7);
            endTime = dateTime.AddDays(-7);
            m_ViewModel.GetWeekStartAndEndTime(dateTime.AddDays(-7), out startTime, out startTime);
            List<HistoryPassengerFlow> ageHistoryPassengerFlows2 = m_ViewModel.GetAgeDurationPassengerFlow(startTime, endTime);

            DataSeries series2 = ChartHelper.GetDataSeries(RenderAs.Line, "上周", ChartValueTypes.Numeric);
            series2.DataMappings.Add(ChartHelper.GetDataMapping("XValue", "Age"));
            series2.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "AllInOut"));
            series2.DataSource = ageHistoryPassengerFlows2;
            vcWeekAgeChart.Series.Add(series2);
        }

        /// <summary>
        /// 周每日客流分时段分布图
        /// </summary>
        private void SetWeekDayChart()
        {
            List<DayOfWeek> dayOfWeeks = new List<DayOfWeek>();

            DateTime dateTime = datePicker.SelectedDate.Value;
            int weekNum = FayshineManager.Instance.GetWeekNumber(dateTime);
            string title1 = GetChartSubTitle();

            DateTime startTime = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, 0, 0, 0);
            DateTime endTime = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, 0, 0, 0);
            m_ViewModel.GetWeekStartAndEndTime(dateTime, out startTime, out endTime);

            dayOfWeeks.Add(DayOfWeek.Monday);
            dayOfWeeks.Add(DayOfWeek.Tuesday);
            dayOfWeeks.Add(DayOfWeek.Wednesday);
            dayOfWeeks.Add(DayOfWeek.Thursday);
            dayOfWeeks.Add(DayOfWeek.Friday);
            dayOfWeeks.Add(DayOfWeek.Saturday);
            dayOfWeeks.Add(DayOfWeek.Sunday);
            var workDaySource = m_ViewModel.GetHistoryPassengerByWeek(false, startTime, endTime, dayOfWeeks);

            Axis xAxis = new Axis();
            DateTime minDateTime = workDaySource.Select(s => s.HistoryTime).Min();
            DateTime maxDateTime = workDaySource.Select(s => s.HistoryTime).Max();
            xAxis.AxisMinimum = minDateTime;
            xAxis.AxisMaximum = maxDateTime;
            if (maxDateTime.Year == minDateTime.Year && maxDateTime.Month == minDateTime.Month &&
                maxDateTime.Day == minDateTime.Day)
            {
                xAxis.ValueFormatString = "HH:mm";
                xAxis.IntervalType = IntervalTypes.Hours;
                xAxis.Interval = 1;
            }
            else
            {
                xAxis.IntervalType = IntervalTypes.Hours;
                xAxis.Interval = 4;
            }
            vcWeekDayDurationChart.AxesX.Add(xAxis);

            Title vcChart1Title = new Visifire.Charts.Title();
            vcChart1Title.Text = startTime.Year + "年第" + weekNum + "周" + title1 + " 每日客流分时段分布图";
            vcWeekDayDurationChart.Titles.Add(vcChart1Title);

            var mondaySeries = GetWorkDayDataSeries(startTime, endTime, DayOfWeek.Monday);
            var tuesdaySeries = GetWorkDayDataSeries(startTime, endTime, DayOfWeek.Tuesday);
            var wedSeries = GetWorkDayDataSeries(startTime, endTime, DayOfWeek.Wednesday);
            var thursSeries = GetWorkDayDataSeries(startTime, endTime, DayOfWeek.Thursday);
            var fridaySeries = GetWorkDayDataSeries(startTime, endTime, DayOfWeek.Friday);
            var satSeries = GetWorkDayDataSeries(startTime, endTime, DayOfWeek.Saturday);
            var sunSeries = GetWorkDayDataSeries(startTime, endTime, DayOfWeek.Sunday);

            vcWeekDayDurationChart.Series.Add(mondaySeries);
            vcWeekDayDurationChart.Series.Add(tuesdaySeries);
            vcWeekDayDurationChart.Series.Add(wedSeries);
            vcWeekDayDurationChart.Series.Add(thursSeries);
            vcWeekDayDurationChart.Series.Add(fridaySeries);
            vcWeekDayDurationChart.Series.Add(satSeries);
            vcWeekDayDurationChart.Series.Add(sunSeries);

        }

        private DataSeries GetWorkDayDataSeries(DateTime startTime, DateTime endTime, DayOfWeek dayOfWeek)
        {
            List<DayOfWeek> dayOfWeeks = new List<DayOfWeek>();
            dayOfWeeks.Add(dayOfWeek);
            var workDaySource = m_ViewModel.GetHistoryPassengerByWeek(false, startTime, endTime, dayOfWeeks);
            int sum = workDaySource.Any() ? workDaySource.Sum(s => s.AllInOut) : 0;

            string title = string.Format("{0} {1} ({2})", 
                GetDateForWeek(startTime, endTime, dayOfWeek).ToShortDateString(),
                GetWeekDayString(dayOfWeek), sum);

            DataSeries series = ChartHelper.GetDataSeries(RenderAs.Line, title, ChartValueTypes.Time);
            series.DataMappings.Add(ChartHelper.GetDataMapping("XValue", "HistoryTime"));
            series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "AllInOut"));
            series.DataSource = workDaySource;

            return series;
        }

        private string GetWeekDayString(DayOfWeek dayOfWeek)
        {
            string weekDay = "星期一";
            switch (dayOfWeek)
            {
                case DayOfWeek.Sunday:
                    weekDay = "星期日";
                    break;
                case DayOfWeek.Monday:
                    weekDay = "星期一";
                    break;
                case DayOfWeek.Tuesday:
                    weekDay = "星期二";
                    break;
                case DayOfWeek.Wednesday:
                    weekDay = "星期三";
                    break;
                case DayOfWeek.Thursday:
                    weekDay = "星期四";
                    break;
                case DayOfWeek.Friday:
                    weekDay = "星期五";
                    break;
                case DayOfWeek.Saturday:
                    weekDay = "星期六";
                    break;
            }

            return weekDay;
        }

        private string GetChartSubTitle()
        {
            string title1 = string.Empty;

            var selectAreaExts = m_ViewModel.AreaExtends.Where(a => a.IsSelected).ToList();
            if (selectAreaExts.Count == 1)
            {
                title1 = selectAreaExts[0].Name;
            }
            else if (selectAreaExts.Count > 1)
            {
                title1 = "各店铺";
            }

            return title1;
        }

        private DateTime GetDateForWeek(DateTime start, DateTime end, DayOfWeek dayOfWeek)
        {
            DateTime a = start;

            while (start <= end)
            {
                if (start.DayOfWeek == dayOfWeek)
                {
                    a = start;
                    break;
                }
                start = start.AddDays(1);
            }

            return a;
        }

        #endregion

        private void btnExport_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog fsd = new SaveFileDialog();
            fsd.Filter = "PDF (*.pdf)|*.pdf|*PNG (*.png)|*.png";

            if (fsd.ShowDialog() == true)
            {
                LocalBusyIndicator indicator = Application.Current.RootVisual as LocalBusyIndicator;
                indicator.IsBusy = true;
                this.Dispatcher.BeginInvoke(delegate()
                {
                    FayshineManager.Instance.ExportToDisk(fsd, spContent);
                });
            }
        }

    }
}
